import axios from 'axios'
import Cookie from 'js-cookie'
import { message } from 'ant-design-vue'
import TypeOfUtils  from '@/utils/data-type-utils'

import { REQ_HEADER_KEY } from '@/enums/request-enums'

// 默认请求超时时间
const DEFALUT_TIME_OUT = 1000 * 30
// 常见axios实例
const axiosServer = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: DEFALUT_TIME_OUT
})
// 证书？？
axiosServer.defaults.withCredentials = false
axiosServer.defaults.xsrfHeaderName= REQ_HEADER_KEY
axiosServer.defaults.xsrfCookieName= REQ_HEADER_KEY

/**
 * 解析url中的参数
 * 
 * @param {String} url 
 * @returns {Object}
 */
function parseUrlParams (url) {
  const params = {}
  if (!url || url === '' || typeof url !== 'string') {
    return params
  }
  const paramsStr = url.split('?')[1]
  if (!paramsStr) {
    return params
  }
  const paramsArr = paramsStr.replace(/&|=/g, ' ').split(' ')
  for (let i = 0; i < paramsArr.length / 2; i++) {
    const value = paramsArr[i * 2 + 1]
    params[paramsArr[i * 2]] = value === 'true' ? true : (value === 'false' ? false : value)
  }
  return params
}


function loadInterceptors (interceptors, options) {
  const {request, response} = interceptors
  request.forEach(item => {
    let {onFulfilled, onRejected} = item
    if (!onFulfilled || !TypeOfUtils.isFunction(onFulfilled)) {
      onFulfilled = config => config
    }
    if (!onRejected || !TypeOfUtils.isFunction(onRejected)) {
      onRejected = error => Promise.reject(error)
    }
    axiosServer.interceptors.request.use(
      config => onFulfilled(config, options),
      error => onRejected(error, options)
    )
  })

  response.forEach(item => {
    let {onFulfilled, onRejected} = item
    if (!onFulfilled || !TypeOfUtils.isFunction(onFulfilled)) {
      onFulfilled = config => config
    }
    if (!onRejected || !TypeOfUtils.isFunction(onRejected)) {
      onRejected = error => Promise.reject(error)
    }
    axiosServer.interceptors.response.use(
      config => onFulfilled(config, options),
      error => onRejected(error, options)
    )
  })

}

/**
 * request 拦截器
 */
axiosServer.interceptors.request.use(config => {
  const { url, xsrfCookieName } = config
  if (url.indexOf('login') === -1 && xsrfCookieName && !Cookie.get(xsrfCookieName)) {
    message.warning('认证 token 已过期，请重新登录')
  }
  return config
}, error => {
  message.error(error.message)
  return Promise.reject(error)
})

export default axiosServer
